const http = require('http')
const fs = require('fs')
const server = http.createServer((request, response) => {
    // response.end('hello ...')
    const { url, method ,headers} = request
    const picReg = new RegExp(/\.(png|jpg|jpeg|gif)$/, "g")
    response.setHeader('Content-Type', 'text/plain; charset=utf-8');
    if (url === '/' && method === 'GET'){
        // 静态页面服务
        fs.readFile('index.html',(err, data) => {
            response.statusCode = 200
            response.setHeader('Content-Type','text/html')
            response.end(data)
        })
    }else if(url === '/users' && method === 'GET'){
        // Ajax服务
        response.writeHead(200,{
            'Content-Type': 'application/json'
        })
        response.end(JSON.stringify({
            name : '我是lixiangyu'
        }))
    }else if(url.match(picReg)){
        // 图片文件服务
        console.log(url)
        console.log(url.match(picReg))
        fs.createReadStream('./'+url).pipe(response)
    }else{
        response.end("<h1>404, the page not found!</h1>")
    }

})
server.listen(8080)